package me.majiajie.pagerbottomtabstrip.internal;

import java.util.ArrayList;
import java.util.List;

import me.majiajie.pagerbottomtabstrip.ItemController;
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener;
import me.majiajie.pagerbottomtabstrip.listener.SimpleTabItemSelectedListener;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.ComponentTransition;
import ohos.app.Context;
import ohos.media.image.PixelMap;

/**
 * 存放自定义项的布局
 */
public class CustomItemLayout extends ComponentContainer implements ItemController, Component.EstimateSizeListener, ComponentContainer.ArrangeListener {

    private final List<BaseTabItem> mItems = new ArrayList<>();
    private final List<OnTabItemSelectedListener> mListeners = new ArrayList<>();
    private final List<SimpleTabItemSelectedListener> mSimpleListeners = new ArrayList<>();

    private int mSelected = -1;

    public CustomItemLayout(Context context) {
        this(context, null);
    }

    public CustomItemLayout(Context context, AttrSet attrs) {
        this(context, attrs, null);
    }

    public CustomItemLayout(Context context, AttrSet attrs, String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setComponentTransition(new ComponentTransition());
        setEstimateSizeListener(this);
        setArrangeListener(this);
    }

    public void initialize(List<BaseTabItem> items, boolean animateLayoutChanges) {
        mItems.clear();
        mItems.addAll(items);

        if (animateLayoutChanges) {
            setComponentTransition(new ComponentTransition());
        }

        // 添加按钮到布局，并注册点击事件
        int size = mItems.size();
        for (int i = 0; i < size; i++) {
            final BaseTabItem tabItem = mItems.get(i);
            tabItem.setChecked(false);
            this.addComponent(tabItem);

            tabItem.setClickedListener(new ClickedListener() {
                @Override
                public void onClick(Component component) {
                    int index = mItems.indexOf(tabItem);
                    if (index >= 0) {
                        setSelect(index);
                    }
                }
            });
        }

        // 默认选中第一项
        mSelected = 0;
        mItems.get(0).setChecked(true);
    }

    @Override
    public boolean onEstimateSize(int widthMeasureSpec, int heightMeasureSpec) {
        final int count = getChildCount();
        int visableChildCount = 0;
        for (int i = 0; i < count; i++) {
            if (getComponentAt(i).getVisibility() != HIDE) {
                visableChildCount++;
            }
        }

        if (visableChildCount == 0) {
            return false;
        }

        final int childWidthMeasureSpec = EstimateSpec.getSizeWithMode(EstimateSpec.getSize(widthMeasureSpec) / visableChildCount, EstimateSpec.PRECISE);
        final int childHeightMeasureSpec = EstimateSpec.getSizeWithMode(Math.max(0, EstimateSpec.getSize(heightMeasureSpec) - getPaddingBottom() - getPaddingTop()), EstimateSpec.PRECISE);

        for (int i = 0; i < count; i++) {
            final Component child = getComponentAt(i);
            if (child.getVisibility() == HIDE) {
                continue;
            }
            child.estimateSize(childWidthMeasureSpec, childHeightMeasureSpec);
        }
        setEstimatedSize(widthMeasureSpec, heightMeasureSpec);
        return true;
    }

    @Override
    public boolean onArrange(int left, int top, int right, int bottom) {
        final int count = getChildCount();
        final int width = right - left;
        final int height = bottom - top;
        // 只支持top、bottom的padding
        final int paddingTop = getPaddingTop();
        final int paddingBottom = getPaddingBottom();
        int used = 0;

        for (int i = 0; i < count; i++) {
            final Component child = getComponentAt(i);
            if (child.getVisibility() == HIDE) {
                continue;
            }
            if (getLayoutDirection() == LayoutDirection.RTL) {
                child.arrange(width - used - child.getEstimatedWidth(), paddingTop, width - used, height - paddingBottom);
            } else {
                child.arrange(used, paddingTop, child.getEstimatedWidth() + used, height - paddingBottom);
            }
            used += child.getEstimatedWidth();
        }
        return true;
    }

    @Override
    public void setSelect(int index) {
        setSelect(index, true);
    }

    @Override
    public void setSelect(int index, boolean needListener) {
        // 重复选择
        if (index == mSelected) {
            if (needListener) {
                for (OnTabItemSelectedListener listener : mListeners) {
                    mItems.get(mSelected).onRepeat();
                    listener.onRepeat(mSelected);
                }
            }
            return;
        }

        // 记录前一个选中项和当前选中项
        int oldSelected = mSelected;
        mSelected = index;

        // 前一个选中项必须不小于0才有效
        if (oldSelected >= 0 && oldSelected < mItems.size()) {
            mItems.get(oldSelected).setChecked(false);
        }

        if (mSelected >= 0 && mSelected < mItems.size()) {
            mItems.get(mSelected).setChecked(true);
        }

        if (needListener) {
            // 事件回调
            for (OnTabItemSelectedListener listener : mListeners) {
                listener.onSelected(mSelected, oldSelected);
            }
            for (SimpleTabItemSelectedListener listener : mSimpleListeners) {
                listener.onSelected(mSelected, oldSelected);
            }
        }
    }

    @Override
    public void setMessageNumber(int index, int number) {
        mItems.get(index).setMessageNumber(number);
    }

    @Override
    public void setHasMessage(int index, boolean hasMessage) {
        mItems.get(index).setHasMessage(hasMessage);
    }

    @Override
    public void addTabItemSelectedListener(OnTabItemSelectedListener listener) {
        mListeners.add(listener);
    }

    @Override
    public void addSimpleTabItemSelectedListener(SimpleTabItemSelectedListener listener) {
        mSimpleListeners.add(listener);
    }

    @Override
    public void setTitle(int index, String title) {
        mItems.get(index).setTitle(title);
    }

    @Override
    public void setDefaultDrawable(int index, PixelMap drawable) {
        mItems.get(index).setDefaultDrawable(drawable);
    }

    @Override
    public void setSelectedDrawable(int index, PixelMap drawable) {
        mItems.get(index).setSelectedDrawable(drawable);
    }

    @Override
    public int getSelected() {
        return mSelected;
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

    @Override
    public String getItemTitle(int index) {
        return mItems.get(index).getTitle();
    }

    @Override
    public boolean removeItem(int index) {
        if (index == mSelected || index >= mItems.size() || index < 0) {
            return false;
        }

        if (mSelected > index) {
            mSelected--;
        }

        this.removeComponentAt(index);
        mItems.remove(index);
        return true;
    }

    @Override
    public void addMaterialItem(int index, PixelMap defaultDrawable, PixelMap selectedDrawable, String title, int selectedColor) {
        // nothing
    }

    @Override
    public void addCustomItem(int index, final BaseTabItem item) {
        item.setChecked(false);
        item.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                int index = mItems.indexOf(item);
                if (index >= 0) {
                    setSelect(index);
                }
            }
        });
        if (index >= mItems.size()) {
            mItems.add(index, item);
            this.addComponent(item);
        } else {
            mItems.add(index, item);
            this.addComponent(item, index);
        }
    }

}
